package cn.signalpha.modules.resource.endpoint;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.resource.builder.oss.OssBuilder;
import cn.signalpha.modules.resource.entity.Attach;
import cn.signalpha.modules.resource.entity.AttachCategory;
import cn.signalpha.modules.resource.service.IAttachService;
import cn.signalpha.modules.resource.service.impl.AttachCategoryServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;

/**
 * 附件表 控制器
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_RESOURCE_NAME + "/attach")
@Api(value = "附件端点", tags = "附件端点")
public class AttachEndpoint extends BaseController {

	private final OssBuilder ossBuilder;
	private final IAttachService attachService;
	private final AttachCategoryServiceImpl attachCategoryService;

	@GetMapping("/page")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "附件分页", notes = "传入attach")
	public R<IPage<Attach>> page(Attach attach, Query query) {
		QueryWrapper<Attach> queryWrapper = Condition.getQueryWrapper(attach);
		queryWrapper.lambda().orderByDesc(Attach::getId);
		return R.data(attachService.page(Condition.getPage(query), queryWrapper));
	}

	@GetMapping("/category/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name="name", dataType = "string", value = "名称"),
	})
	@ApiOperation(value = "分类列表", notes = "")
	public R<List<AttachCategory>> list(@ApiIgnore @RequestParam Map<String, Object> params) {
		List<AttachCategory> list = attachCategoryService.list(Wrappers.<AttachCategory>query().lambda()
			.eq(ObjectUtil.isNotEmpty(params.get("name")), AttachCategory::getName, params.get("name"))
			.orderByDesc(AttachCategory::getSort).orderByDesc(AttachCategory::getId)
		);
		return R.data(list);
	}

	@PostMapping("/remove")
	@ApiOperationSupport(order = 50)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		Func.toLongList(ids).forEach(id -> {
			Attach attach = attachService.getById(id);
			ossBuilder.template().removeFile(attach.getName());
			attachService.removeById(id);
		});
		return R.status(true);
	}

}
